package me.rvj.dao;

import me.rvj.entity.User;
import me.rvj.util.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @program: JavaWeb
 * @description: 用户工具类
 * @author: Rv_Jiang
 * @date: 2021/7/2 9:48
 */
public class UserDao {

    private UserDao() {
    }

    private static final String getUserListSQL = "select * from userlist;";
    private static final String addUserSQL = "insert into userlist(userName,password) values(?,?);";


    /**
     * @description 获取用户列表
     * @author Rv_Jiang
     * @date 2021/7/2 10:14
     */
    public static List<User> getUserList() {
        List<User> userList = new ArrayList<User>();
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;


        try {
            conn = DBUtil.getConnection();

            ps = conn.prepareStatement(getUserListSQL);

            rs = ps.executeQuery();
            while (rs.next()) {
                String userName = rs.getString(1);
                String password = rs.getString(2);
                Integer uuid = rs.getInt(3);
                userList.add(new User(userName, password, uuid));
            }
            return userList;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            DBUtil.clear(conn, ps, rs);
        }

        return userList;
    }

    /**
     * @description 新增用户
     * @author Rv_Jiang
     * @date 2021/7/2 10:17
     */
    public static boolean addUser(String userName, String password) {
        Connection conn = null;
        PreparedStatement ps = null;
        try {
            conn = DBUtil.getConnection();
            ps = conn.prepareStatement(addUserSQL);
            ps.setString(1, userName);
            ps.setString(2, password);

            if(ps.executeUpdate()==1){
                return true;
            }else{
                return false;
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            DBUtil.clear(conn,ps,null);
        }

        return false;
    }




}
